import tools from '../tools/tools'
import {ase} from '../tools/encryption'
import { ctx } from '../../entrance/inter';
let time = tools.time;

if(module) module.exports = {
  get,
  set,
  encryption,
  decryption,
}

export default {
  get,
  set,
  encryption,
  decryption,
}

//获取cookie
export function get(ctx:ctx,key?:string){
  let cookie = pars(ctx);
  if(key===undefined)return cookie;
  return cookie[key];
}

export function set(ctx:ctx,name:any,value:any,obj:any={
  httpOnly:"httpOnly=httpOnly",
  path:"/",
},data:any=[]){
  if(typeof name == 'string'){data.push({name,value,...obj})} else data=name;
  data.forEach((e,index)=>{
    let {name,value,httpOnly="httpOnly=httpOnly",path="/",time} = e;
    time?(expires_time(time)):(time=expires_time());
    (httpOnly==='none' || httpOnly==='') && (httpOnly='')
    data[index]=`${name}=${encryption(value)};${httpOnly};path=${path};expires=${time};`;
    data[index]=data[index].replace(/;;/g,";");
  })
  ctx.$res.setHeader('Set-Cookie',data);
};

//解析出请求头中的cookie
function pars(ctx:ctx,cookie={}){
  if(!ctx.$req.headers.cookie)return {};
  ctx.$req.headers.cookie.split(/ ;|; /g).filter(e=>e).forEach(e => {
    let a = e.split("=");
    // 解密
    let value = decryption(a[1]);
    
    cookie[a[0]]=value?value:a[1];  
  });
  return cookie;
}


//设置cook的时间
function expires_time(times=(time()+(1000*60*60*24))){
  return (new Date(times)).toUTCString();
}

//cookie加密
export function encryption(str){
  if(str===undefined){new Error('加密内容为空')}
  return "cgem."+ase.encrypt(str);
}

//cookie解密
export function decryption(str){
  if(!str)return undefined;
  //先判断是否为框架加密的cookie
  if(str.startsWith("cgem.")){
    str = str.substring(5)
  }else{return str}
  return ase.decrypt(str);
}